/*
 * ------------------------------------------------------------------
 * Copyright © 2017 Hangzhou DtDream Technology Co.,Lt d. All rights reserved.
 * ------------------------------------------------------------------
 * Product: DataStudio
 * Module Name:
 * Date Created: 2017-10-23
 * Description:
 * ------------------------------------------------------------------
 * Modification History
 * DATE Name Description
 * ------------------------------------------------------------------
 * 2017-10-23 八神 h0248
 * ------------------------------------------------------------------
 */

package org.xukai.common.util;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class EncryptUtil {

    /**
     * 加密算法
     */
    public static String CIPHER_ALGORITHM = "AES"; // optional value AES/DES/DESede
    private static final String confusePasswd = new String(getKey(null).getEncoded());

    /**
     * 密码加密
     *
     * @throws Exception
     */
    public static String encryptPasswd(String content) {
        return encrypt(content, confusePasswd);
    }

    /**
     * 加密
     */
    public static String encrypt(String data, String key) {
        try {
            SecureRandom sr = new SecureRandom();
            Key secureKey = getKey(key);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr);
            byte[] bt = cipher.doFinal(data.getBytes());
            String strS = new BASE64Encoder().encode(bt);
            return replaceEscapeChar(strS);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException("Create cipher failed", e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException("Init cipher failed", e);
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("Encrypt data failed", e);
        }
    }

    /**
     * 生成key
     */
    public static Key getKey(String strKey) {
        try {
            if (strKey == null) {
                strKey = "";
            }
            KeyGenerator generator = KeyGenerator.getInstance(CIPHER_ALGORITHM);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(strKey.getBytes());
            generator.init(128, secureRandom);
            return generator.generateKey();
        } catch (Exception e) {
            throw new RuntimeException("Init key error!");
        }
    }

    /**
     * 加密后替换掉换行符
     */
    private static String replaceEscapeChar(String sql) {
        sql = sql.replaceAll("\n", "&&n");
        sql = sql.replaceAll("\r", "&&r");
        return sql;
    }

    /**
     * 密码解密
     *
     * @throws Exception
     */
    public static String decryptPasswd(String encryptPasswd) throws IOException, GeneralSecurityException {
        return decrypt(encryptPasswd, confusePasswd);
    }

    /**
     * 解密
     */
    public static String decrypt(String message, String key) throws IOException, GeneralSecurityException {
        message = restoreEscapeChar(message);
        SecureRandom sr = new SecureRandom();
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        Key secureKey = getKey(key);
        cipher.init(Cipher.DECRYPT_MODE, secureKey, sr);
        byte[] res = new BASE64Decoder().decodeBuffer(message);
        res = cipher.doFinal(res);
        return new String(res);
    }

    /**
     * 解密前恢复换行符
     */
    private static String restoreEscapeChar(String sql) {
        sql = sql.replaceAll("&&n", "\n");
        sql = sql.replaceAll("&&r", "\r");
        return sql;
    }

    /**
     * Base64加密
     */
    public static String encryptBase64(String pwd) {
        return Base64.encodeBase64String(pwd.getBytes());
    }

    /**
     * Base64解密
     */
    public static String decryptBase64(String pwd) {
        return new String(Base64.decodeBase64(pwd.getBytes()));
    }

    public static boolean ifBase64(String val) {
        byte[] key = Base64.decodeBase64(val);
        String strs = new String(key);
        String result= Base64.encodeBase64String(strs.getBytes());
        if(result.equals(val)){
            return true;
        }
        return false;
    }
}
